package com.zl.hyzg.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;


import java.util.HashMap;
import java.util.Map;


public class SendMessage {

    // 产品名称:云通信短信API产品,开发者无需替换
    //static final String product = "Dysmsapi";
    // 产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // 自己的AK(在阿里云访问控制台寻找)AccessKey ID
    static final String accessKeyId = "LTAI4G56APr3ERwa9kFosYwo";
    // 自己的AK(在阿里云访问控制台寻找)AccessKey Secret
    static final String accessKeySecret = "LLTDDdi8QDLqrOHhLIzHR9kxhZis4K";

    public static boolean sendSms(String telephone, String checkCode) throws ClientException {

        // 可自助调整超时时间
        // System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        // System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        // 初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        //DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(domain);
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        //System.out.println(telephone);

        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", telephone);//设置电话号码
        request.putQueryParameter("SignName", "化运中国平台");//设置签名
        request.putQueryParameter("TemplateCode", "SMS_205392760");//设置模板
        HashMap<String, String> params = new HashMap<>();
        params.put("code", checkCode);
        String paramsJSON = JSONObject.toJSONString(params);
        request.putQueryParameter("TemplateParam", paramsJSON);//设置模板参数，json格式
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            Map map = JSONObject.parseObject(response.getData(), Map.class);
            String code = (String) map.get("Code");
            if ("OK".equalsIgnoreCase(code)) {
                return true;
            }
            //{"Message":"OK","RequestId":"7B562B28-A4F9-417C-8CCE-E7E988EA8C20","BizId":"316818172776024297^0","Code":"OK"}
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
